﻿using Server.Common;
using Spire.Doc;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;

namespace Server.Utils
{
    /// <summary>
    /// PDF文件转换
    /// </summary>
    public static class PdfFormatUtil
    {
        /// <summary>
        /// 分割指定页码PDF文件
        /// </summary>
        /// <param name="path"></param>
        /// <param name="checkPages"></param>
        /// <returns></returns>
        public static Dictionary<int, byte[]> SplitFile(string path, object[] checkPages)
        {
            try
            {
                using (PdfDocument pdfFile = new PdfDocument(path))
                {
                    Dictionary<int, byte[]> pdfPages = new Dictionary<int, byte[]>();
                    PdfPageBase page;
                    foreach (int index in checkPages)
                    {
                        if (index <= 0 || index > pdfFile.Pages.Count) throw new Exception($"{new FileInfo(path).Name }未找到第{index}页");

                        var pageIndex = index - 1;

                        using (PdfDocument childPdfFile = new PdfDocument())
                        {
                            page = childPdfFile.Pages.Add(pdfFile.Pages[pageIndex].Size, new PdfMargins(0));
                            pdfFile.Pages[pageIndex].CreateTemplate().Draw(page, new PointF(0, 0));

                            var pdfStream = childPdfFile.SaveToStream(Spire.Pdf.FileFormat.PDF);
                            pdfPages.Add(index, pdfStream.Length > 0 ? FileUtil.StreamToBytes(pdfStream[0]) : null);
                        }
                    }

                    return pdfPages;
                };
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 合并指定页码PDF文件
        /// </summary>
        /// <param name="path"></param>
        /// <param name="checkPages"></param>
        /// <returns></returns>
        public static byte[] MergeFile(string path, object[] checkPages, Spire.Pdf.FileFormat fileFormat = Spire.Pdf.FileFormat.PDF)
        {
            try
            {
                Log4Util.LogInstance.Info(typeof(PdfFormatUtil), "开始合并PDF文件");
                using (PdfDocument pdfFile = new PdfDocument(path))
                {
                    Log4Util.LogInstance.Info(typeof(PdfFormatUtil), "源文件Spire.PDF对象创建完成");
                    PdfPageBase page;
                    using (PdfDocument childPdfFile = new PdfDocument())
                    {
                        Log4Util.LogInstance.Info(typeof(PdfFormatUtil), "目标文件Spire.PDF对象创建完成");
                        foreach (var item in checkPages)
                        {
                            int index = Convert.ToInt32(item);
                            if (index <= 0 || index > pdfFile.Pages.Count) throw new Exception($"{new FileInfo(path).Name }未找到第{index }页");

                            var pageIndex = index - 1;

                            page = childPdfFile.Pages.Add(pdfFile.Pages[pageIndex].Size, new PdfMargins(0));
                            Log4Util.LogInstance.Info(typeof(PdfFormatUtil), $"使用第{pageIndex}页信息新建PDF页");
                            pdfFile.Pages[pageIndex].CreateTemplate().Draw(page, new PointF(0, 0));
                            Log4Util.LogInstance.Info(typeof(PdfFormatUtil), $"第{pageIndex}页内容拷贝完成");
                        }
                        var pdfStream = childPdfFile.SaveToStream(fileFormat);
                        if (pdfStream.Length > 0)
                        {
                            Log4Util.LogInstance.Info(typeof(PdfFormatUtil), $"PDF转换完成，文件大小：{pdfStream[0].Length}");
                        }
                        else
                        {
                            Log4Util.LogInstance.Info(typeof(PdfFormatUtil), $"未获取到Word文件流");
                        }

                        return pdfStream.Length > 0 ? FileUtil.StreamToBytes(pdfStream[0]) : null;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 合并多个PDF文件
        /// </summary>
        /// <param name="paths"></param>
        /// <returns></returns>
        public static PdfDocument MergePdfFiles(string[] paths)
        {
            var pdf = PdfDocument.MergeFiles(paths);
            float minWidth = pdf.Pages[0].Size.Width;
            for (int i = 0; i < pdf.Pages.Count; i++)
            {
                if (minWidth > pdf.Pages[i].Size.Width)
                {
                    minWidth = pdf.Pages[i].Size.Width;
                }
            }

            //创建一个新的PdfDocument实例
            PdfDocument pdfFile = new PdfDocument();


            //遍历所有PDF 页面     
            foreach (PdfPageBase page in pdf.Pages)
            {
                SizeF pageSize = new SizeF(minWidth, page.Size.Height / (page.Size.Width / minWidth));
                //设置新页面大小为A2, 设置新的页边距
                PdfPageBase newPage = pdfFile.Pages.Add(pageSize, new PdfMargins(0, 0));
                newPage.Canvas.DrawTemplate(page.CreateTemplate(), new PointF(0, 0), pageSize);
            }

            return pdfFile;
        }


        public static byte[] MergeWordFiles(string[] paths, Spire.Doc.FileFormat format = Spire.Doc.FileFormat.Doc)
        {
            Document document = null;
            try
            {
                foreach (var item in paths)
                {
                    if (document == null)
                    {
                        document = new Document(item);
                    }
                    else
                    {
                        document.InsertTextFromFile(item, Path.GetExtension(item).ToLower() == ".doc" ? Spire.Doc.FileFormat.Doc : Spire.Doc.FileFormat.Docx);
                    }

                }
                MemoryStream convertImgStream = new MemoryStream();
                document.SaveToStream(convertImgStream, format);
                return FileUtil.StreamToBytes(convertImgStream);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (document != null)
                {
                    document.Dispose();
                    document.Close();
                }
            }

        }

        /// <summary>
        /// 转换指定页码PDF为Image
        /// </summary>
        /// <param name="path"></param>
        /// <param name="checkPages"></param>
        /// <returns></returns>
        public static Dictionary<int, Image> ToImages(string path, object[] checkPages)
        {
            try
            {
                using (PdfDocument pdfFile = new PdfDocument(path))
                {
                    Dictionary<int, Image> pdfImages = new Dictionary<int, Image>();

                    foreach (var item in checkPages)
                    {
                        int index = Convert.ToInt32(item);
                        if (index <= 0 || index > pdfFile.Pages.Count) throw new Exception($"{new FileInfo(path).Name }未找到第{index }页");
                        var pageIndex = index - 1;

                        var a = pdfFile.SaveAsImage(pageIndex);
                        pdfImages.Add(index, null);
                    }
                    return pdfImages;
                };
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 转换指定页码PDF为Word
        /// </summary>
        /// <param name="path"></param>
        /// <param name="checkPages"></param>
        /// <param name="fileFormat"></param>
        /// <returns></returns>
        public static byte[] ToWord(string path, object[] checkPages, Spire.Pdf.FileFormat fileFormat = Spire.Pdf.FileFormat.DOC)
        {
            try
            {
                return MergeFile(path, checkPages, fileFormat);
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        public static bool ToExcel(string path, object[] pageIndexs = null)
        {
            return true;
        }


        public static byte[] ToPDF(string path)
        {
            try
            {
                //新建PDF文档，添加一页
                using (PdfDocument doc = new PdfDocument())
                {
                    PdfPageBase page = doc.Pages.Add();

                    //加载图片到Image对象
                    Image image = Image.FromFile(path);

                    float imageWidth = (float)image.Width;
                    float imageHeight = (float)image.Height;

                    var scale = imageHeight / imageWidth;

                    if (page.Canvas.Size.Width < imageWidth)
                    {
                        imageWidth = page.Canvas.Size.Width - 100;
                        imageHeight = imageWidth * scale;
                    }
                    if (page.Canvas.Size.Height < imageHeight)
                    {
                        imageHeight = page.Canvas.Size.Height - 100;
                        imageWidth = imageHeight / scale;
                    }

                    Size size = new Size(image.Width, image.Height);

                    Bitmap scaledImage = new Bitmap(image, size);
                    //加载缩放后的图片到PdfImage对象
                    PdfImage pdfImage = PdfImage.FromImage(scaledImage);

                    //在指定位置绘入图片
                    page.Canvas.DrawImage(pdfImage, 0f, 0f, imageWidth, imageHeight);

                    //保存文档
                    var stream = doc.SaveToStream(Spire.Pdf.FileFormat.PDF);
                    return stream.Length > 0 ? FileUtil.StreamToBytes(stream[0]) : null;
                };
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
